package com.kay.bean;

import com.kay.anno.RPCReference;
import com.kay.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @Description:
 * @Author: Kay
 * @CreateDate: 2021/8/27$ 22:18$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/8/27$ 22:18$
 */
@Component
public class RPCBean implements BeanPostProcessor {
    @Autowired
    private RpcClientProxy proxy;

    /**
     * 在 postProcessAfterInitialization 生成增强对象（代理对象）
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 获取所有增加了 @RPCReference 注解的对象
            if (field.getAnnotation(RPCReference.class) != null) {
                Class<?> aClass = field.getType();
                // 对对象进行RPC增强
                Object proxy = this.proxy.createProxy(aClass);
                try {
                    field.setAccessible(true);
                    field.set(bean, proxy); // 为当前对象注入的 属性进行增强
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                System.out.println("当前对象 ： " + beanName + " bean" + bean.toString());
                return bean;
            }
        }
        return null;
    }
}
